package com.nxuer.controllers.pkg01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;

@RestController
@RequestMapping("/RestfulApi")
public class RelaysStatus {
    @GetMapping("/RelaysStatus")
    String rs() {

        try {
            String url = "http://iot.0531yun.cn/wsjc/app/GetRelays?deviceKey=23272";
            HttpGet get = new HttpGet(url);
            get.setHeader("userId", "9372");
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse httpResponse = httpClient.execute(get);
            String strResponse =  EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonResponse1 = JSON.parseObject(strResponse);
            url = "http://iot.0531yun.cn/wsjc/app/GetRelays?deviceKey=827";
            get.setURI(URI.create(url));
            httpResponse = httpClient.execute(get);
            strResponse = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonResponse2 = JSON.parseObject(strResponse);
            if (jsonResponse2.getInteger("code").equals(1000) && jsonResponse1.getInteger("code").equals(1000)) {
                JSONObject rep = new JSONObject();
                rep.put("code", 1000);
                JSONArray ja = jsonResponse1.getJSONArray("data");
                ja.addAll(jsonResponse2.getJSONArray("data"));
                rep.put("data", ja);
                return rep.toJSONString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"code\": 1001, \"message\": \"boom\"}";
    }
}